package com.jishuo.base.service;

import com.github.pagehelper.PageHelper;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.Pagination;
import com.jishuo.base.bean.vo.MenuVO;
import com.jishuo.base.bean.vo.UserVO;
import com.jishuo.base.config.AppConfig;
import com.jishuo.base.dao.MenuMapper;
import com.jishuo.base.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜单管理
 */
@Slf4j
@Service
public class MenuService {
    @Resource
    private MenuMapper menuMapper;

    // 菜单列表，分页
    public List<MenuVO> listMenu(MenuVO menu, Pagination pagination) {
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return this.menuMapper.listMenu(menu);
    }

    /** 设置用户可用菜单id、url */
    public void setUserMenu(UserVO user) {
        String ids = ",";
        List<String> urls = new ArrayList<>();
        List<MenuVO> all = this.menuMapper.listMenu(new MenuVO());
        for (int i=0;i<all.size();i++) {
            MenuVO vo = all.get(i);
            if (user.getMenuId().contains("," + vo.getMenuId() + ",")) {
                ids += vo.getMenuId() + ",";
                if (StringUtil.isNotEmpty(vo.getUrl())) urls.add(vo.getUrl());
            }
        }
        user.setMenuId(ids);
        user.setMenuUrls(StringUtils.toStringArray(urls));
    }

    /**
     * 根据用户权限获得菜单树
     * @param user
     * @return
     */
    public List<MenuVO> listMenuTree(UserVO user) {
        List<MenuVO> menus = new ArrayList<>();
        if (user == null || user.getMenuId().length() < 2) return menus;
        List<MenuVO> all = this.menuMapper.listMenu(new MenuVO());
        for (int i=0;i<all.size();i++) {
            MenuVO vo = all.get(i);
            if (user.getMenuId().indexOf("," + vo.getMenuId() + ",") >= 0) menus.add(vo);
        }
        return this.getSubMenu("0", menus);
    }

    /**
     * 从菜单列表（全）中，获取下级菜单。递归调用
     * @param pid 父级菜单ID
     * @param all 菜单列表
     * @return
     */
    private List<MenuVO> getSubMenu(String pid, List<MenuVO> all) {
        List<MenuVO> list = new ArrayList<>();
        for (int i = 0; i < all.size(); i++) {
            MenuVO vo = all.get(i);
            if (pid.equals(vo.getParentId())) {
                vo.setSubMenus(this.getSubMenu(vo.getMenuId(), all));
                list.add(vo);
            }
        }
        return list;
    }

    /**
     * 新增菜单
     * @param menu
     * @return
     */
    public BaseResult addMenu(MenuVO menu) {
        try {
            return (this.menuMapper.addMenu(menu) > 0) ? new BaseResult() : new BaseResult(ErrorCodeEnum.DB_ERR);
        } catch (Exception e) {
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        }
    }

    /**
     * 更新菜单
     * @param menu
     * @return
     */
    public BaseResult saveMenu(MenuVO menu) {
        try {
            return (this.menuMapper.saveMenu(menu) > 0) ? new BaseResult() : new BaseResult(ErrorCodeEnum.DB_ERR);
        } catch (Exception e) {
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        }
    }

    /**
     * 删除菜单
     * @param menuId 菜单ID
     * @return
     */
    public BaseResult deleteMenu(String menuId) {
        try {
            MenuVO vo = new MenuVO();
            vo.setParentId(menuId);
            if (this.menuMapper.listMenu(vo).size() > 0) return new BaseResult(AppConfig.CUSTOM_ERR, "存在子菜单，不能删除");

            this.menuMapper.deleteMenu(menuId);
            return new BaseResult();
        } catch (Exception e) {
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        }
    }

    /**
     * 根据ID获得菜单
     * @param menuId
     * @return
     */
    public MenuVO getMenu(String menuId) {
        return this.menuMapper.getMenu(menuId);
    }
}
